package com.sinoglobal.wallet.activity;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.sinoglobal.wallet.R;
import com.sinoglobal.wallet.adapter.W_BankSeleAdapter;
import com.sinoglobal.wallet.api.RemoteImpl;
import com.sinoglobal.wallet.entity.W_SinoBaseEntity;
import com.sinoglobal.wallet.task.MyAsyncTask;
import com.sinoglobal.wallet.util.NetWorkUtil;
import com.sinoglobal.wallet.view.InnerListView;

import android.content.Intent;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

/**
 * 添加银行卡
 * @author lijingjing
 * @createdate 2015-10-22 上午9:33:40
 * @Description: TODO(用一句话描述该类做什么)
 */
public class W_MyAddbankActivity extends W_SinoBaseActivity{
	private ListView  bank_select_listView;
	private EditText addbank_Num_EditText, 
	addbank_Name_EditText; //所属银行  卡号  持卡人
	private TextView addBankOK_Button,addBank_txt;//下一步
	private W_BankSeleAdapter adapter;
	private List list;//总列表
	private List sourseList = new ArrayList();//搜索列表
	private Map map = new HashMap();
	private JSONObject jsonObj;
	private Object object;
	private ImageView addBank_mohu, addBank_check_img;//模糊图片  正在验证图片;
	private RelativeLayout addBank_txt_right_img;//所属银行卡右边的图片;
	private LinearLayout addBank_check_layout;//正在验证layout
	private Animation bankChek_anim;
	
	private boolean isClickFlag=true;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.wallet_mine_addbank_activity);
		mTemplateTitleText.setText("我的银行卡");

		jsonAs();
		JSONArray jsonArray;
		list = new ArrayList();
		try {
			jsonArray = new JSONArray(jsonAs());
			int iSize = jsonArray.length();
			for (int i = 0; i < iSize; i++) {
				jsonObj = jsonArray.getJSONObject(i);
				list.add(jsonObj.get("s"));//将解析出来的赋给list中
				map.put(jsonObj.get("s"), jsonObj.get("key"));
			}
			//			Log.d("TAG", map+"..." + map.size());
			//			Log.d("TAG", list+"..." + list.size());
		} catch (JSONException e) {
			e.printStackTrace();
		}
		init();
	}
	private void  init(){
		addbank_Num_EditText = (EditText) findViewById(R.id.addbank_Num_EditText);
		addbank_Num_EditText.setInputType(InputType.TYPE_CLASS_NUMBER);
		addbank_Name_EditText = (EditText) findViewById(R.id.addbank_Name_EditText);
		addBankOK_Button = (TextView) findViewById(R.id.addBankOK_Button);
		addBank_txt = (TextView) findViewById(R.id.addBank_txt);
		addBankOK_Button.setOnClickListener(this);
		addBank_mohu = (ImageView) findViewById(R.id.addBank_mohu);
		addBank_check_layout = (LinearLayout) findViewById(R.id.addBank_check_layout);
		addBank_check_img = (ImageView) findViewById(R.id.addBank_check_img);

	//	addBank_editText = (EditText) findViewById(R.id.addBank_editText);
		addBank_txt_right_img = (RelativeLayout) findViewById(R.id.addBank_txt_right_img);
		bank_select_listView = (ListView) findViewById(R.id.bank_select_listView);

		//禁止输入数字
		addbank_Name_EditText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

				String editable = addbank_Name_EditText.getText().toString();  
				String str = stringFilter(editable.toString());
				if(!editable.equals(str)){
					addbank_Name_EditText.setText(str);
					//设置新的光标所在位置  
					addbank_Name_EditText.setSelection(str.length());
				} 
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int  count,
					int after) {

			}
			@Override
			public void afterTextChanged(Editable s) {

			}
		});
		addBank_txt_right_img.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(isClickFlag){
					bank_select_listView.setVisibility(View.VISIBLE);
					addBank_mohu.setVisibility(View.VISIBLE);
					isClickFlag=false;
					setAdapter();
				}else{
					bank_select_listView.setVisibility(View.INVISIBLE);
					addBank_mohu.setVisibility(View.INVISIBLE);
					isClickFlag=true;
				}
			}
		});
/*
		addBank_editText.addTextChangedListener(new TextWatcher() {

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
				addBank_editText.setSelection(arg0.length());//设置光标一直在最后
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {

			}

			@Override
			public void afterTextChanged(Editable arg0) {
				if(addBank_editText.getText().toString().trim().length() > 0 ){
					bank_select_listView.setVisibility(View.VISIBLE);
					addBank_mohu.setVisibility(View.VISIBLE);
					setForInfos();
				}else{
					bank_select_listView.setVisibility(View.INVISIBLE);
					addBank_mohu.setVisibility(View.INVISIBLE);
				}
			}
		});*/


		bank_select_listView.setOnItemClickListener(new OnItemClickListener() {


			@Override
			public void onItemClick(AdapterView<?> paramAdapterView,
					View paramView, int paramInt, long paramLong) {
				addBank_txt.setText(list.get(paramInt).toString().trim());
				object = map.get(addBank_txt.getText().toString().trim());
				bank_select_listView.setVisibility(View.INVISIBLE);
				addBank_mohu.setVisibility(View.INVISIBLE);
			}
		});
	}
/*	*//**
	 * 搜索
	 *//*
	public void setForInfos() {
		sourseList.clear();
		if (list != null) {
			for (int i = 0; i < list.size(); i++) {// 银行名称
				if (list.get(i).toString().contains(addBank_editText.getText().toString().trim())) {
					sourseList.add(list.get(i));
				}
			}
			setChildAdapter();

		}else{
			bank_select_listView.setVisibility(View.INVISIBLE);
			addBank_mohu.setVisibility(View.INVISIBLE);
		}
	}*/
	/**
	 * 搜索适配器
	 */
	/*public void setChildAdapter() {
		if (sourseList != null && sourseList.size()!=0 && 
				isContainChinese(addBank_editText.getText().toString()) == false) {
			bank_select_listView.setVisibility(View.VISIBLE);
			addBank_mohu.setVisibility(View.VISIBLE);
			adapter = new W_BankSeleAdapter(W_MyAddbankActivity.this);
			bank_select_listView.setAdapter(adapter);
			adapter.setList(sourseList);
		}else{
			bank_select_listView.setVisibility(View.INVISIBLE);
			addBank_mohu.setVisibility(View.INVISIBLE);
				showToast("请输入正确的银行名称");
		}
	}*/
	/**
	 * 搜索适配器
	 */
	public void setAdapter() {
			bank_select_listView.setVisibility(View.VISIBLE);
			addBank_mohu.setVisibility(View.VISIBLE);
			adapter = new W_BankSeleAdapter(W_MyAddbankActivity.this);
			bank_select_listView.setAdapter(adapter);
			adapter.setList(list);
			mesureParams();
	}

	private void mesureParams() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		int mScreenWidth = dm.widthPixels;
		LayoutParams params = bank_select_listView.getLayoutParams();
		
		if (adapter == null) {
			return;
		}
		params.width = mScreenWidth;
		View listItem = adapter.getView(0, null, bank_select_listView);
		listItem.measure(0, 0);
		int itemHeight = listItem.getMeasuredHeight();
		if (list.size()<7) {
			params.height =itemHeight*list.size()+ (bank_select_listView.getDividerHeight() * (adapter.getCount() - 1));  
		}else{
			params.height = itemHeight*7+ (bank_select_listView.getDividerHeight() * 6);
		}
		bank_select_listView.setLayoutParams(params);
		
	}
	//解析assets文件下的bank.json文件
	private String jsonAs(){
		AssetManager s =  getResources().getAssets();
		try{
			InputStream is = s.open("bank.json");
			byte [] buffer = new byte[is.available()] ; 
			is.read(buffer);  
			String json = new String(buffer,"utf-8"); 
			is.close();
			JSONObject obj;
			try {
				obj = new JSONObject(json);
				String title = obj.getString("banklist");
				//								Log.d(".....", "TITLE:" + title);
				if(title!=null&&title.toCharArray().length>0){
					return title;
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}  

		}catch(IOException e){
			e.printStackTrace();
		}
		return null;
	}

	private void getAddBank(){
		MyAsyncTask<W_SinoBaseEntity> task = new MyAsyncTask<W_SinoBaseEntity>(false,this,true) {

			@Override
			public W_SinoBaseEntity before(Void... params) throws Exception {
				// TODO 测试接口
				return RemoteImpl.getInstance().getAddBank(W_MyAddbankActivity.this, object + "", addbank_Num_EditText.getText().toString().trim(), addbank_Name_EditText.getText().toString().trim());
			}

			@Override
			public void after(W_SinoBaseEntity result) {

				if (result.getCode().equals("100")) {
					if(result != null){
						sendWithdrawalBroadcast();//通知W_WithDrawalActivity刷新添加银行卡信息
						finish();
						showToast("添加成功");
						addBank_check_img.clearAnimation();
						addBank_check_layout.setVisibility(View.INVISIBLE);
					}
				} else {
					showToast(result.getMsg());
					addBank_check_img.clearAnimation();
					addBank_check_layout.setVisibility(View.INVISIBLE);
				}
			}

			@Override
			public void exception() {
			}
		};
		task.execute();
	}
	private void sendWithdrawalBroadcast() {
		Intent intent = new Intent();
		intent.setAction("com.sinoglobal.wallet.receiver.withdrawal");
		intent.putExtra("type", 201);
		sendBroadcast(intent);
	}	
	
	@Override
	public void onClick(View v) {
		int id = v.getId();
		if(id == R.id.addBankOK_Button){
			if(addBank_txt.getText().toString().trim().equals("")){
				showToast("请输入所属银行");
			}else if(addbank_Num_EditText.getText().toString().trim().equals("")){
				showToast("请输入银行卡号");
			}else if(addbank_Name_EditText.getText().toString().trim().equals("")){
				showToast("请输入姓名");
			}else if(addbank_Num_EditText.getText().toString().trim().length() < 16){
				showToast("卡号输入有误");
			}else{
				addBank_check_layout.setVisibility(View.VISIBLE);
				bankChek_anim = AnimationUtils.loadAnimation(W_MyAddbankActivity.this, R.anim.w_rotata_show);
				addBank_check_img.startAnimation(bankChek_anim);
				if(object != null) {
					getAddBank();
				}else{
					showToast("请输入正确银行卡信息");
					addBank_check_img.clearAnimation();
					addBank_check_layout.setVisibility(View.INVISIBLE);
				}
			}
		}else if(id==R.id.wallet_noData){
			 if(NetWorkUtil.getNetWorkInfoType(getApplicationContext())==NetWorkUtil.NONE){
					showToast("请检查网络是否连接！");	
					 loadError(true);
					}else{
						loadError(false);;
					}
		}
	}
	// 只有包含中文（没有其他）
	public static boolean isContainChinese(String str) {

		Pattern p = Pattern.compile("[u4e00-u9fa5]");
		Matcher m = p.matcher(str);
		if (m.find()) {
			return true;
		}
		return false;
	}

	// 只允许字母、汉字      
	public static String stringFilter(String str)throws PatternSyntaxException{     
		String   regEx  =  "[^a-zA-Z\u4E00-\u9FA5]";                     
		Pattern   p   =   Pattern.compile(regEx);     
		Matcher   m   =   p.matcher(str);     
		return   m.replaceAll("").trim();     
	}
}
